package com.hcrazy.manchester.app.services;

import java.util.List;

import com.hcrazy.manchester.app.jdbc.NewsSortDAO;
import com.hcrazy.manchester.app.pojo.ErrorMsg;
import com.hcrazy.manchester.app.pojo.NewsSort;
import com.hcrazy.manchester.app.utils.Constant;

public class NewsSortService {

	private NewsSortDAO newsSortDAO;

	public NewsSortDAO getNewsSortDAO() {
		return newsSortDAO;
	}

	public void setNewsSortDAO(NewsSortDAO newsSortDAO) {
		this.newsSortDAO = newsSortDAO;
	}

	public ErrorMsg addOrUpdateNewsSort(NewsSort sort) throws Exception{
		ErrorMsg msg = new ErrorMsg();
		msg.setCode(Constant.SUCCESS);//success
		
		if(sort.getSortId()>0){
			newsSortDAO.updateNewsSort(sort);
		}else{
			newsSortDAO.addNewsSort(sort);
		}
		
		return msg;
	}
	
	/**
	 * 获取二层的树状结构
	 * @param type
	 * @return
	 * @throws Exception
	 */
	public List<NewsSort> getTwoLayerSorts(int type) throws Exception{
		List<NewsSort> list = newsSortDAO.listAllSorts(type);
		NewsSort root = new NewsSort();
		root.setSortId(0);
		for(NewsSort sort:list){
			if(sort.getParentId() == root.getSortId()){
				for(NewsSort sort1:list){
					if(sort1.getParentId() == sort.getSortId()){
						sort.getChildren().add(sort1);
					}
				}
				root.getChildren().add(sort);
			}
		}
		
		return root.getChildren();
	}
	
	public List<NewsSort> getAllSorts(int type,int parentId) throws Exception{
		List<NewsSort> list = newsSortDAO.listAllSorts(type);
		NewsSort root = new NewsSort();
		root.setSortId(parentId);
		setChildren(root, list);
		
		return root.getChildren();
	}
	
	private void setChildren(NewsSort root,List<NewsSort> list){
		for(NewsSort sort:list){
			if(sort.getParentId() == root.getSortId()){
				setChildren(sort, list);
				root.getChildren().add(sort);
			}
		}
	}
	
	public NewsSort getSortById(int sortId) throws Exception{
		return newsSortDAO.getById(sortId);
	}
	
	public String delNewsSort(int sortId) throws Exception{
		
		//删除子分类
		newsSortDAO.delNewsSortByParentId(sortId);
		
		//删除本分类
		newsSortDAO.delNewsSort(sortId);
		
		//清空所有父分类不存在的分类
		
		return null;
	}
	
}
